package cn.tworice.upload.service;

import cn.tworice.upload.constand.UploadConst;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.util.Base64;

@Component
public class DownloadService {

    @Value("${tworice.file.cryption:false}")
    private Boolean cryption;
    /**
     * 获取目标地址文件的Base64码
     * @param path 文件绝对路径
     * @return java.lang.String Base64码
     **/
    public String getBase64(String path) {
        Base64.Encoder encoder = Base64.getEncoder();
        File file = new File(path);
        try (FileInputStream fis=new FileInputStream(file)){
            byte[] temp = new byte[(int) file.length()];
            fis.read(temp, 0, (int) file.length());
            temp = encoder.encode(temp);
            return UploadConst.imageBase64 + new String(temp);
        } catch (FileNotFoundException e) {
            throw new cn.tworice.upload.exception.FileNotFoundException();
        } catch (IOException e) {
            throw new RuntimeException("系统异常");
        }
    }

    public void outputResponse(File file, HttpServletResponse response) throws Exception {
        if(this.cryption){
            // 判断是否需要解密
            file = FileEncryptionUtil.decodeFileFromBase64(file);
        }
        InputStream in = Files.newInputStream(file.toPath());
        response.setContentLength(in.available());
        OutputStream out = response.getOutputStream();
        byte[] b = new byte[1024];
        int len = 0;
        while((len = in.read(b))!=-1){
            out.write(b, 0, len);
        }
        out.flush();
        out.close();
        in.close();
    }

    /**
     * 预览图片未找到资源，返回404
     */
    public void previewNotFound(HttpServletResponse response) {
        // 创建一个图片
        int width = 400;
        int height = 200;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        // 获取Graphics2D对象
        Graphics2D g2d = image.createGraphics();

        // 设置背景颜色和绘制颜色
        g2d.setColor(Color.BLACK);
        g2d.fillRect(0, 0, width, height);
        g2d.setColor(Color.WHITE);
        g2d.setFont(new Font("微软雅黑", Font.BOLD, 30));

        // 在图片上绘制文字
        String message = "没有找到图片";
        FontMetrics fontMetrics = g2d.getFontMetrics();
        int stringWidth = fontMetrics.stringWidth(message);
        int stringHeight = fontMetrics.getAscent();
        g2d.drawString(message, (width - stringWidth) / 2, (height + stringHeight) / 2);

        // 释放资源
        g2d.dispose();

        try {
            // 设置响应类型
            response.setContentType("image/jpeg");

            // 将图片写入响应输出流
            ImageIO.write(image, "jpeg", response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
